/**
 * Copyright 2009 Adam Ruggles.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.google.code.sapien.dao.jpa;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import com.google.code.sapien.dao.DiscussionDAO;
import com.google.code.sapien.model.Discussion;
import com.google.inject.Inject;

/**
 * A JPA implementation of the {@link com.google.code.sapien.dao.DiscussionDAO} interface.
 * @author Adam
 * @version $Id$
 * 
 * Created on May 7, 2009 at 7:48:14 PM 
 */
public class DiscussionJpaDAO extends AbstractJpaDAO<Discussion> implements	DiscussionDAO {
	/**
	 * Constructs a discussion JPA data access object.
	 * @param entityManager The entity manager.
	 */
	@Inject
	public DiscussionJpaDAO(final EntityManager entityManager) {
		super(entityManager);
	}

	/**
	 * {@inheritDoc}
	 * @see com.google.code.sapien.dao.DiscussionDAO#getCount()
	 */
	public int getCount() {
		return ((Number) getEntityManager().createNamedQuery("discussion.getCount").getSingleResult()).intValue();
	}

	/**
	 * {@inheritDoc}
	 * @see com.google.code.sapien.dao.DiscussionDAO#getCount(java.lang.Integer)
	 */
	public int getCount(final Long categoryId) {
		final Query query = getEntityManager().createNamedQuery("discussion.getCountCategoryId");
		query.setParameter("categoryId", categoryId);
		return ((Number) query.getSingleResult()).intValue();
	}

	/**
	 * {@inheritDoc}
	 * @see com.google.code.sapien.dao.DiscussionDAO#list(int, int)
	 */
	@SuppressWarnings("unchecked")
	public List<Discussion> list(final int offset, final int maxResults) {
		final Query query = getEntityManager().createNamedQuery("discussion.list");
		query.setFirstResult(offset).setMaxResults(maxResults);
		return query.getResultList();
	}

	/**
	 * {@inheritDoc}
	 * @see com.google.code.sapien.dao.DiscussionDAO#list(java.lang.Integer, int, int)
	 */
	@SuppressWarnings("unchecked")
	public List<Discussion> list(final Long categoryId, final int offset, final int maxResults) {
		final Query query = getEntityManager().createNamedQuery("discussion.listCategoryId");
		query.setParameter("categoryId", categoryId);
		query.setFirstResult(offset).setMaxResults(maxResults);
		return query.getResultList();
	}
}
